<template>
  <div class="mod-prod prod-list-mod">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"
        @submit.prevent
      >
        <!-- 表单项 -->
        <div class="input-row">
          <el-form-item label="商城名称:">
            <el-input
              v-model="searchForm.shopName"
              type="text"
              clearable
              placeholder="商城名称"
            />
          </el-form-item>

          <el-form-item label="文案标题:">
            <el-input
              v-model="searchForm.title"
              type="text"
              clearable
              placeholder="文案标题"
            />
          </el-form-item>

          <el-form-item label="文案类型:">
            <el-select
              v-model="searchForm.articleType"
              clearable
              placeholder="文案类型"
              style="width: 100%"
            >
              <el-option
                v-for="(item, index) in typeList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            :label="$t('product.status')+':'"
          >
            <el-select
              v-model="searchForm.status"
              clearable
              :placeholder="$t('product.status')"
            >
              <el-option
                v-for="(item, index) in stateList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="文案标签:"
          >
            <el-select
              v-model="searchForm.articleTags"
              clearable
              placeholder="文案标签"
            >
              <el-option
                v-for="(item, index) in tagList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="置顶:"
          >
            <el-select
              v-model="searchForm.isTop"
              clearable
              placeholder="置顶"
            >
              <el-option
                :label="$t('publics.no')"
                :value="'0'"
              />
              <el-option
                :label="$t('publics.yes')"
                :value="'1'"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="创建时间:"
          >
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              clearable
              :range-separator="$t('date.tip')"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
            />
          </el-form-item>

          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="onResetSearch"
            >
              {{ $t('product.reset') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>

    <!-- 主体内容 -->
    <div class="main-container">
      <!-- 表格 -->
      <div class="table-con prod-table">
        <el-table
          ref="prodListTableRef"
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row"
          style="width: 100%"
          @sort-change="handleSortableChange"
          @selection-change="onSelectSome"
        >
          <!-- <el-table-column
            type="selection"
            width="55"
          /> -->
          <el-table-column
            prop="shopName"
            label="商城名称"
            min-width="200"
            show-overflow-tooltip
          />

          <el-table-column
            prop="title"
            label="文案标题"
            min-width="200"
            show-overflow-tooltip
          />

          <el-table-column
            prop="subTitle"
            label="文案副标题"
            min-width="250"
            show-overflow-tooltip
          />

          <el-table-column
            prop="articleType"
            label="文案类型"
          >
            <template #default="scope">
              {{ typeList.find(d => d.value == scope.row.articleType)?.label }}
            </template>
          </el-table-column>

          <el-table-column
            prop="articleTags"
            label="文案标签"
            width="200"
            show-overflow-tooltip
          />

          <el-table-column
            prop="publishTime"
            label="发布时间"
            width="200"
          />

          <el-table-column
            prop="createdBy"
            label="作者"
          />

          <el-table-column
            prop="status"
            label="状态"
            width="80"
          >
            <template #default="scope">
              {{ stateList.find(d => d.value == scope.row.status)?.label }}
            </template>
          </el-table-column>

          <el-table-column
            prop="isTop"
            label="置顶"
            width="60"
          >
            <template #default="scope">
              {{ scope.row.isTop == '0' ? '否' : '是' }}
            </template>
          </el-table-column>

          <el-table-column
            prop="visitNum"
            label="阅读量"
            width="100"
          />

          <el-table-column
            fixed="right"
            align="center"
            :label="$t('publics.operating')"
            width="230"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('copywriting:manage:view')"
                  class="default-btn text-btn"
                  @click="onView(scope.row)"
                >
                  查看
                </div>

                <div
                  v-if="isAuth('copywriting:manage:down')"
                  class="default-btn text-btn"
                  @click="onDown(scope.row)"
                >
                  {{ scope.row.status == 1 ? '违规下架' : '上架' }}
                </div>

                <div
                  v-if="isAuth('copywriting:manage:delete')"
                  class="default-btn text-btn"
                  @click="onDelete(scope.row.id)"
                >
                  {{ $t("text.delBtn") }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <el-pagination
        v-if="dataList.length"
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>

    <el-dialog
      v-model="showDetail"
      title="查看"
      top="5%"
      width="1000px"
      class="fix-dialog"
    >
      <el-form
        ref="addFormRef"
        label-width="100px"
        :model="detailForm"
      >
        <el-form-item
          label="文案标题"
        >
          <span class="detail-text">{{ detailForm.title }}</span>
        </el-form-item>

        <el-form-item
          label="文案副标题"
        >
          <span class="detail-text">{{ detailForm.subTitle }}</span>
        </el-form-item>

        <el-form-item
          label="文案类型"
        >
          {{ typeList.find(d => d.value == detailForm.articleType)?.label }}
        </el-form-item>

        <el-form-item
          label="文案标签"
        >
          <span class="detail-text">{{ detailForm.articleTags }}</span>
        </el-form-item>

        <el-form-item
          v-if="detailForm.articleType==0"
          label="关联产品"
        >
          <span class="detail-text">{{ detailForm.prodIds }}</span>
        </el-form-item>

        <el-form-item
          label="文案封面"
        >
          <imgs-show
            :src="detailForm.articleCover"
          />
        </el-form-item>

        <el-form-item
          label="文案内容"
        >
          <div
            v-rich="detailForm.articleContent"
            class="detail-text"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'
import { typeList, stateList } from './data'

let tempSearchForm = null // 保存上次点击查询的请求条件
let theParams = null // 保存上次点击查询的请求条件
const dateRange = ref([])
const dataList = ref([])
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})

const tagList = ref([])
const userStore = useUserStore()
const getTagList = () => {
  http({
    url: http.adornUrl('/articleTag/list'),
    method: 'get',
    params: http.adornParams({
      shopId: userStore.shopId
    })
  }).then(({ data }) => {
    tagList.value = data.map(d => {
      return {
        label: d.tagName,
        value: d.tagName
      }
    })
  })
}
const searchForm = reactive({})

onMounted(() => {
  const parPage = useRoute().query.page
  if (parPage) {
    const { total, currentPage, pageSize } = JSON.parse(decodeURI(parPage))
    page.total = total
    page.currentPage = currentPage
    page.pageSize = pageSize
  }
  getDataList(page)
  getTagList()
})

// 获取数据列表
const getDataList = (pageParam, newData = false) => {
  if (page) {
    const size = Math.ceil(page.total / page.pageSize)
    page.currentPage = (page.currentPage > size ? size : page.currentPage) || 1
  }
  theParams = JSON.parse(JSON.stringify(searchForm))
  tempSearchForm = {
    current: pageParam == null ? page.currentPage : pageParam.currentPage,
    size: pageParam == null ? page.pageSize : pageParam.pageSize
  }
  if (dateRange.value && dateRange.value.length == 2) {
    theParams.beginTime = dateRange.value[0]
    theParams.endTime = dateRange.value[1]
  }
  http({
    url: http.adornUrl('/article/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        tempSearchForm,
        theParams
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
    // 末尾页数据为空重新请求
    if (!dataList.value.length && page.currentPage > 1) {
      page.currentPage = 1
      getDataList()
    }
  })
}

const showDetail = ref(false)
const detailForm = ref({})
const onView = (row) => {
  showDetail.value = true
  detailForm.value = { ...row }
  http({
    url: http.adornUrl('/prod/prod/listByProdIds'),
    method: 'post',
    data: http.adornData({
      shopId: row.shopId,
      prodIds: row.prodIds
    })
  }).then(({ data }) => {
    if (data && data.length) {
      detailForm.value.prodIds = data.map(d => d.prodName).join()
    }
  })
}

// 删除
const dataListSelections = ref([])
const onDelete = (id) => {
  const ids = id ? [id] : dataListSelections.value.map(item => {
    return item.prodId
  })
  ElMessageBox.confirm(`${$t('seckill.isDeleOper')}?`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl(`/article/${id}`),
      method: 'delete',
      data: http.adornData({})
    }).then(() => {
      page.total = page.total - ids.length
      ElMessage({
        message: $t('publics.operation'),
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
  })
    .catch(() => { })
}

// 条件查询
const onSearch = (newData = false) => {
  page.currentPage = 1
  getDataList(page, newData)
}

// 回调刷新
const refreshChange = () => {
  getDataList(page)
}

// 多选变化
const selectAll = ref(false) // 是否全选
const onSelectSome = (val) => {
  dataListSelections.value = val
  selectAll.value = val.length === dataList.value.length
  if (dataList.value.length === 0) {
    selectAll.value = false
  }
}

// 全选按钮
const prodListTableRef = ref(null)
const onSelectAll = () => {
  prodListTableRef.value?.toggleAllSelection()
}

/**
 * 重置表单
 * @param {String} formName 表单名称
 */
const searchFormRef = ref(null)
const onResetSearch = () => {
  searchFormRef.value.resetFields()
  for (const k in searchForm) {
    searchForm[k] = ''
  }
  dateRange.value = []
}

const onDown = (row) => {
  ElMessageBox.confirm('确认执行此操作吗?', $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    http({
      url: '/article',
      method: 'put',
      data: http.adornData({
        id: row.id,
        status: row.status == '1' ? '2' : '1',
        isTop: row.status == '1' ? '0' : row.isTop
      })
    }).then(() => {
      ElMessage.success('操作成功')
      getDataList(page)
    })
  })
}

const onTop = (row) => {
  http({
    url: '/article/top',
    method: 'post',
    data: http.adornData({
      id: row.id,
      shopId: userStore.shopId,
      articleType: row.articleType,
      isTop: row.isTop == '0' ? '1' : '0'
    })
  }).then(() => {
    ElMessage.success('操作成功')
    getDataList(page)
  })
}

const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList()
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList()
}
</script>

<style lang="scss" scoped>
.prod-list-mod {
  .main-container {
    .table-con .table-cell-con .table-cell-text{
      word-break: break-all
    }
    .operation-bar {
      position: relative;
      .all-check-btn {
        margin-right: 10px;
      }
      .had-selected {
        font-size: 12px;
        margin-right: 10px;
      }
      .tag-text {
        font-size: 12px;
      }
      .batch-setting-dropdown {
         .batch-setting-btn {
           padding-right: 15px;
           margin-right: 0;
          &:hover {
            .arrow::after {
              border-top: 1px solid #155bd4;
              border-right: 1px solid #155bd4;
            }
          }
          &.active {
            color: #155bd4;
            border-color: #155bd4;
            .arrow::after {
              border-top: 1px solid #155bd4;
              border-right: 1px solid #155bd4;
              transform: rotate(-45deg);
              top: 0;
              right: 0;
              transition: all .2s linear;
            }
          }
          .arrow {
            position: relative;
            margin-left: 9px;
            &::after{
              position: relative;
              top: -3px;
              right: 0;
              transition: all .2s linear;
              content: '';
              display: inline-block;
              width: 6px;
              height: 6px;
              border-top: 1px solid #656565;
              border-right: 1px solid #656565;
              transform: rotate(135deg);
            }
          }
        }
      }
    }
  }
  :deep(.export-load) {
    top: -50% !important;
  }

  .detail-text{
    word-break: break-all;
  }
}

:deep(.fix-dialog .el-dialog__body){
  height: calc(90vh - 110px);
  overflow: auto;
}
</style>
